<script>
import cookie from 'js-cookie';
import get from 'lodash-es/get.js';
import find from 'lodash-es/find.js';
import debounce from 'lodash-es/debounce.js';
import { getPlugins } from '@gis/lib/components/AMap/js/AMapUtils.js';
import { useUserInfoStore } from '@gis/lib/pinia/userInfo.js';
import { getRegionCoordinate, getYardRegionCoordinate } from '@gis/lib/api';
import { callVideoConferencing, showVideoConferencingDialog } from '@gis/lib/components/tx-webrtc/index.js';
import { getVideoConferencingRoomId } from '@gis/lib/components/tx-webrtc/index.js';
import { bdToGd } from './js/translator.js';
import PolygonLayer from './js/PolygonLayer.js';
import env from '@gis/lib/env.js';
import { getToken } from '@gis/lib/utils/token.js';
// import { bdToGd } from '@gis/modules/components/gis-map/js/translator.js';
// import PolygonLayer from '@gis/modules/components/gis-map/js/PolygonLayer.js';

export function formatPathData(data = {}) {
  if (typeof data !== 'object' || !data) return;
  if (data.Q && data.R) return [data.R, data.Q];
  if (data.lng && data.lat) return [data.lng, data.lat];
  if (data.longitude && data.latitude) return [data.longitude, data.latitude];
}

export function isReginGroupEmpty(list, key = 'coordinate') {
  return !list || !list.length || list.every((item) => !item[key] || !item[key].length);
}

export default {
  name: 'map-polygon',
  render() {
    return null;
  },
  props: {
    mapGetter: { type: Function, default: undefined },
    autoDistrictSearch: { type: Boolean, default: true },
  },
  setup() {
    const userInfoStore = useUserInfoStore();
    const account_type = get(userInfoStore, 'userData.type');
    const yard_id = get(userInfoStore, 'userData.yardId');
    const { area_code, area_name, area_code_level } = userInfoStore;
    const area_level = area_code_level('');
    return { area_code, area_name, area_code_level, area_level, account_type, yard_id };
  },
  async created() {
    this.map = this.mapGetter();
    const fieldsMap = {
      strokeColor: 'region_color',
      fillColor: 'region_color',
      label: 'region_name',
      labelPosition: 'center',
    };
    this.areaLayer = new PolygonLayer({
      map: this.map,
      label: { show: false },
      polygon: { hoverEnable: true, style: { zIndex: 200 } },
      replaceFields: fieldsMap,
    });
    this.yardLayer = new PolygonLayer({
      map: this.map,
      label: { show: false },
      polygon: { hoverEnable: true, style: { zIndex: 250 } },
      replaceFields: fieldsMap,
    });
    this.communityLayer = new PolygonLayer({
      map: this.map,
      label: {
        show: true,
        getText: (data) => {
          const region_name = get(data, 'region_name') || '';
          const textData = get(this.communityLayer, 'textData');
          const num = get(textData, region_name) || '';
          return num ? region_name + '（' + num + '人）' : region_name;
        },
      },
      polygon: { hoverEnable: true, style: { zIndex: 300 } },
      replaceFields: fieldsMap,
      onClick: (e) => this.goNextLevel(e),
      onLabelClick: (e) => this.goNextLevel(e),
    });
    this.gridLayer = new PolygonLayer({
      map: this.map,
      label: {
        show: true,
        getText: (data) => {
          const name = get(data, 'gridding_people.name', '');
          const phone = get(data, 'gridding_people.phone', '');
          return `<div style="text-align: center;line-height: 1.1">
                    <div style="font-size: 1.1em">${get(data, 'region_name', '')}</div>
                    ${name ? '<div style="opacity: 0.6">（' + name + ' ' + phone + '）</div>' : ''}
                  </div>`;
        },
      },
      polygon: { hoverEnable: true, style: { zIndex: 350 } },
      replaceFields: fieldsMap,
      onLabelClick: (e) => {
        const data = e.target.getExtData();
        const name = get(data, 'gridding_people.name', '');
        const account = get(data, 'gridding_people.account', '');
        const roomId = getVideoConferencingRoomId(this.area_code);
        if (name && account) {
          callVideoConferencing({ account: account, name: name, roomId: roomId });
          showVideoConferencingDialog(roomId);
        }
      },
    });
    this.jqGridLayer = new PolygonLayer({
      map: this.map,
      label: { show: true },
      replaceFields: fieldsMap,
    });

    this.$vbus.$on('toggleMapAreaPolygon', (visible) => {
      this.areaLayer.layer.setMap(visible ? this.map : null);
    });
    this.$vbus.$on('toggleMapCommunityPolygon', (visible) => {
      this.communityLayer.layer.setMap(visible ? this.map : null);
    });
    this.$vbus.$on('toggleMapGridPolygon', (visible) => {
      this.gridLayer.layer.setMap(visible ? this.map : null);
    });
    // this.$vbus.$on('mapJQPolygon', this.jqPolygon); // 警情区域 - 目前只有猛追湾街道有，移动到猛追湾项目里面
    this.$vbus.$on('mapFitPolygon', this.mapFitPolygon);

    this.$vbus.$on('renderGridPolygonTexts', (data) => {
      /* for 保和重点人群在网格上显示区域内重点人员数量 */
      this.communityLayer.textData = data;
      this.communityLayer.render();
    });

    this.$watch(
      () => this.$route,
      () => {
        this.init();
      },
      { immediate: true }
    );

    if (this.account_type == 2) {
      /* 物管账号 */
      this.$watch(
        () => this.yard_id,
        async function (val) {
          if (val) {
            await this.getYardArea();
            this.mapFitPolygon('yardLayer');
          }
        },
        { immediate: true }
      );
    } else {
      this.$watch(
        () => this.area_code,
        async function (val) {
          if (val) {
            await this.getAreaAsync();
            await this.communityPolygon();
            this.gridsPolygon().catch();
            this.mapFitPolygon();
          }
        },
        { immediate: true }
      );
    }
  },
  unmounted() {
    this.$vbus.$off('toggleMapAreaPolygon');
    this.$vbus.$off('toggleMapCommunityPolygon');
    this.$vbus.$off('toggleMapGridPolygon');
    this.$vbus.$off('mapJQPolygon');
    this.$vbus.$off('mapFitPolygon');
  },
  beforeDestroy() {
    this.$vbus.$off('toggleMapAreaPolygon');
    this.$vbus.$off('toggleMapCommunityPolygon');
    this.$vbus.$off('toggleMapGridPolygon');
    this.$vbus.$off('mapJQPolygon');
    this.$vbus.$off('mapFitPolygon');
  },
  methods: {
    // 路由变化控制区域显示和隐藏
    init() {
      const { meta } = this.$route;
      let areaController = get(meta, 'areaController', true);
      let communityController = get(meta, 'communityController', true);
      let gridController = get(meta, 'gridController');

      if (typeof areaController === 'boolean') {
        this.areaController = areaController;
        this.layerShow('areaLayer', areaController);
      }
      if (typeof communityController === 'boolean') {
        this.communityController = communityController;
        this.layerShow('communityLayer', communityController);
      }
      if (typeof gridController === 'boolean') {
        this.gridController = gridController;
        this.layerShow('gridLayer', gridController);
      }
    },
    layerShow(layerName, visible) {
      this[layerName].layer.setMap(visible ? this.map : null);
    },
    // 物管账号
    async getYardArea() {
      if (!this.yard_id) return;
      let data = await this.handleCommonRes(getYardRegionCoordinate, this.yard_id);
      // console.log(data);
      data = data.map((item) => {
        const coordinate = item.coordinate || [];
        return {
          center: [],
          path: coordinate.map((item) => bdToGd(item.lng, item.lat)),
        };
      });
      // console.log(this.areaRegion);
      this.yardLayer.render(data);
      this.setBuildingStyle(this.yardLayer.layer.getOverlays());
    },
    // 其他账号
    async getAreaAsync() {
      const data = await this.getRegionAsync(async () => {
        const params = {
          area_code: this.area_code,
          is_contain_oneself: 1, //1包含自己
          range_type: 6, //6仅查询自己区域
        };
        return await this.handleCommonRes(getRegionCoordinate, params);
      }, this.autoDistrictSearch);
      this.areaLayer.render(data);
      this.areaLayer.layer.setOptions({ zIndex: 20, strokeOpacity: 0.9 });
      this.setBuildingStyle(this.areaLayer.layer.getOverlays());
      // 路由控制改图层是否显示
      this.layerShow('areaLayer', this.areaController);
    },
    async communityPolygon() {
      let data = await this.getRegionAsync(async () => {
        const params = {
          area_code: this.area_code,
          range_type: 1, //1查询下级
          // 判断当前登录账号级别（区 - 街道）（街道 - 社区）
          area_level: this.area_level, //查询指定级别的区域范围
          area_type: 'D0138_1', //行政区域
        };
        return await this.handleCommonRes(getRegionCoordinate, params);
      }, false);
      // 网格 - 白莲池诚运中心（非景区页面，不展示熊猫基地区域）
      data = data.filter((item) => {
        return item.area_code != '86.51.01.08.10.10';
      });
      this.communityLayer.render(data);

      this.layerShow('communityLayer', this.communityController);
    },
    async gridsPolygon() {
      // 4区级账号 - 社区
      // 5街道账号 - 网格
      const data = await this.getRegionAsync(async () => {
        const params = {
          area_code: this.area_code,
          range_type: this.area_level == 5 ? 8 : 1, //8:网格 1:下级 2:同级
          // is_gridding: 1, //是否查询网格对应管理网格员信息 0.不返回 1.返回
          area_level: this.area_level == 5 ? 6 : this.area_level + 1, //查询指定级别的区域范围 - 6:社区、5:街道、4:区
        };
        return await this.handleCommonRes(getRegionCoordinate, params);
      }, false);
      this.gridLayer.render(data);
      this.layerShow('gridLayer', this.gridController);
    },
    // 警情图 - 网格
    async jqPolygon(show) {
      if (!this.jqGridReady) {
        this.jqGridReady = this.getRegionAsync(async () => {
          const params = {
            region_type: 4,
            area_code: this.area_code,
          };
          return await this.handleCommonRes(getRegionCoordinate, params);
        }, false);
        const data = await this.jqGridReady;
        this.jqGridLayer.render(data);
      }
      await this.jqGridReady;
      if (show === true) {
        this.communityLayer.layer.setMap(null);
        this.jqGridLayer.layer.setMap(this.map);
      } else {
        this.jqGridLayer.layer.setMap(null);
        this.communityLayer.layer.setMap(this.map);
      }
    },
    async getRegionAsync(api, autoDistrictSearch) {
      const data = await api();
      if (!isReginGroupEmpty(data, 'coordinate')) {
        return data.map((item) => {
          return Object.assign(item, {
            center: bdToGd.apply(null, [item.longitude, item.latitude]),
            path: item.coordinate.map((subitem) => bdToGd.apply(null, formatPathData(subitem))).filter(Boolean),
          });
        });
      } else if (autoDistrictSearch === true) {
        return await new Promise((resolve) => {
          this.getPathByDistrictSearch(this.area_name, 'district').then((searchData) => {
            const areaRegion = searchData.boundaries.map((path) => ({ path }));
            console.log('autoDistrictSearch area region: ', areaRegion);
            resolve(areaRegion);
          });
        });
      }
      return [];
    },
    goNextLevel(e) {
      const data = e.target.De.extData;
    },
    async getPathByDistrictSearch(area_name, level = 'province') {
      if (!this.district) {
        this.district = await getPlugins('DistrictSearch', {
          subdistrict: 1, //获取边界不需要返回下级行政区
          extensions: 'all', //返回行政区边界坐标组等具体信息
          level: level, //查询行政级别为 country：国家,province：省/直辖市,city：市,district：区/县,biz_area：商圈
        });
      }
      return await new Promise((resolve) => {
        this.district.setLevel(level);
        this.district.search(area_name, (status, result) => {
          const list = result ? result.districtList || [] : [];
          const res = typeof list[0] === 'object' && list[0] ? list[0] : {};
          resolve({
            boundaries: res.boundaries || [],
            districtList: res.districtList || [],
          });
        });
      });
    },
    setBuildingStyle(polygons) {
      if (!polygons || !polygons.length) {
        return;
      }
      const areaSize = polygons.reduce((res, item) => {
        return res + item.getArea();
      }, 0);
      // console.log("区域面积: ", areaSize / 1000000 + "平方千米");
      if (areaSize && areaSize / 1000000 > 20) {
        console.warn(`区域面积过大 ${areaSize / 1000000}平方千米！`);
      }
      // console.warn(`区域面积 ${areaSize / 1000000}平方千米！`);
      if (!this.buildingLayer) {
        this.buildingLayer = find(this.map.getLayers(), (item) => {
          return item.CLASS_NAME === 'AMap.Buildings';
        });
      }
      if (this.buildingLayer) {
        this.buildingLayer.setStyle({
          hideWithoutStyle: true, //是否隐藏设定区域外的楼块
          areas: polygons.map((item) => {
            return {
              //围栏
              //visible:false,//是否可见
              rejectTexture: false, //是否屏蔽自定义地图的纹理
              /* TODO: 非常重要!!! 这里的色值前两位是透明度,后6位是正常的色值 */
              color1: 'ee3db99c', //楼顶颜色
              /* TODO: 非常重要!!! 这里的色值前两位是透明度,后6位是正常的色值 */
              color2: 'ff032c22', //楼面颜色
              path: item.getPath(),
            };
          }),
        });
      }
    },
    mapFitPolygon(layers = 'areaLayer') {
      const layerNames = Array.isArray(layers) ? layers : [layers];
      const polygons = layerNames.reduce((res, name) => {
        if (!this[name] || !this[name].layer) return res;
        return res.concat(this[name].layer.getOverlays());
      }, []);
      this.map.setFitView(polygons);
    },
  },
};
</script>

<style scoped></style>
